package usbcali.edu.co.pqrs.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import usbcali.edu.co.pqrs.dataaccess.dao.IUsuariosInternosDAO;
import usbcali.edu.co.pqrs.modelo.UsuariosInternos;

@Scope("singleton")
@Component("PqrsAuthenticationProvider")
public class PqrsAuthenticationProvider implements AuthenticationProvider {
	/**
	 * Implementacion de la seguridad propia
	 */
	
	@Autowired
	private IUsuariosInternosDAO usuariosInternosDAO;
	

	@Transactional(readOnly=true) 
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {

		String name = authentication.getName();
		String password = authentication.getCredentials().toString();
		String query = "SELECT idUsuInterno FROM UsuariosInternos WHERE login = '"
				+ name + "' AND contrasena = '"+ password+"'";
		
		List<UsuariosInternos> lista = usuariosInternosDAO.find(query);
				
		if (lista.size()!=0) {
			
			final List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
			grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));			
			final UserDetails principal = new User(name, password, grantedAuths);
			final Authentication auth = new UsernamePasswordAuthenticationToken(
					principal, password, grantedAuths);
			return auth;
		} else {
			return null;
		}
	}

	/**
	 * Este metodo se llama primero cuando se autentica un usuario
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}


}
